import { i18n } from "@/i18n";
import { formDesign } from "@/views/formgen/components/FormDesign/hooks/useFormDesign";
import { useItemTinymceHook } from "@/views/formgen/components/FormDesign/FormItem/hooks/useItemTinymceHook";
import { computed, nextTick } from "vue";

interface Option {
  label: string;
  value: number | string;
  type: string;
}

export function useFormOption(props?: any) {
  const addDefaultOption = () => {
    let max = 1;
    if (props.item.config.options) {
      max = Math.max(...props.item.config.options.map((item: Option) => item.value), 1) + 1;
    }
    props.item.config.options.push({
      label: i18n.global.t("formgen.option.optionSet"),
      type: "option",
      value: max
    });
    nextTick(() => {
      createTinymceEditor(`${props.item.vModel}-${max}`);
    });
  };

  const addInputOption = () => {
    let max = 1;
    if (props.item.config.options) {
      max = Math.max(...props.item.config.options.map((item: Option) => item.value), 1) + 1;
    }
    props.item.config.options.push({
      label: i18n.global.t("formgen.option.others"),
      type: "input",
      value: max
    });
    nextTick(() => {
      createTinymceEditor(`${props.item.vModel}-${max}`);
    });
  };

  // 禁用操作 非静态数据时不允许编辑
  const disabledOperation = computed(() => {
    return props.item.config.optionsType != 0;
  });

  // 删除选项
  const deleteOption = (index: number) => {
    props.item.config.options.splice(index, 1);
  };

  const { activeData } = formDesign;

  const changeOptionLabel = (id: string, content: string) => {
    // id由题目id-选项id组成  现在规则只有选中的题目能编辑 所以我们直接取选项id
    const optionId = id.split("-")![1];
    if (!optionId) {
      return;
    }
    const index = activeData.value?.config?.options.findIndex((item: Option) => item.value == optionId);
    if (index != -1) {
      activeData.value!.config!.options[index].label = content;
    }
  };

  const { createTinymceEditor } = useItemTinymceHook(changeOptionLabel);

  return {
    addDefaultOption,
    addInputOption,
    deleteOption,
    changeOptionLabel,
    disabledOperation
  };
}
